﻿using System;
using BloggerAutoPosterService.Engine.Models;
using BloggerAutoPosterService.Engine.Net;
using BloggerAutoPosterService.Engine.Utils;

namespace BloggerAutoPosterService.Engine.Core
{
    public class ParseFeedAddToDB : IDataParser
    {
        #region Fields (2)

        readonly IRedirectFinder _redirectFinder;
        readonly IServiceConfig _serviceConfig;

        #endregion Fields

        #region Constructors (1)

        public ParseFeedAddToDB(IServiceConfig serviceConfig, IRedirectFinder redirectFinder)
        {
            _serviceConfig = serviceConfig;
            _redirectFinder = redirectFinder;
        }

        #endregion Constructors

        #region Properties (1)

        public Action<NewsRecord> OnNewsRecord { set; get; }

        #endregion Properties

        #region Methods (1)

        // Public Methods (1) 

        public void SaveFeedData(bool throwException = false)
        {
            try
            {
                if (_serviceConfig.FeedToParse == null || _serviceConfig.FeedToParse.Length == 0) return;

                foreach (var feedToParse in _serviceConfig.FeedToParse)
                {
                    if (string.IsNullOrWhiteSpace(feedToParse)) continue;

                    var rssItems = RssReader.GetEntries(feedToParse);
                    var date = DateTime.Now.ToString("dd-MM-yyyy");

                    foreach (var item in rssItems)
                    {
                        var url = item.Link;
                        url = UrlUtils.FindOrigianlLink(_serviceConfig, _redirectFinder, url);
                        var record = new NewsRecord
                                {
                                    AddDate = date.EscapeXml(),
                                    Author = item.Author.EscapeXml(),
                                    Link = url.EscapeXml(),
                                    Title = item.Title.EscapeXml(),
                                    UrlHash = item.Link.SHA1(),
                                    Annotation = item.Annotation
                                };
                        new XmlDB(_serviceConfig).AddNewRecord(record);

                        if (OnNewsRecord != null) OnNewsRecord(record);
                    }
                }
            }
            catch (Exception ex)
            {
                new Logger(_serviceConfig).WriteLine(ex);
                if (throwException) throw;
            }
        }

        #endregion Methods
    }
}
